import { PropertyConverter } from '@ohos/dataorm';
import List from '@ohos.util.List';
import { SpanRepresentation, toSpans } from './SpanRepresentation';
import { ListItem, toListItem } from './ListItem';

interface Serializable {
  toString(): string;
}

function convert2Str(list: List<Serializable>): string {
  // ! : we assume char '+' will not appear in the string
  let res = ""
  for (let obj of list) {
    res += obj.toString() + "+"
  }
  return res
}

function split(str: string): List<string> {
  let strArr = str.split('+')
  let res = new List<string>()
  for (let arrObj of strArr) {
    res.add(arrObj)
  }
  return res
}

export class LabelConverter extends PropertyConverter<List<string>,string> {
  convertToEntityProperty(databaseValue: string): List<string> {
    let strList = split(databaseValue)
    return strList
  }

  convertToDatabaseValue(entityProperty: List<string>): string {
    return convert2Str(entityProperty)
  }
}

export class SpansConverter extends PropertyConverter<List<SpanRepresentation>,string> {
  convertToEntityProperty(databaseValue: string): List<SpanRepresentation> {
    let strList = split(databaseValue)
    let list = new List<SpanRepresentation>()
    for (let str of strList) {
      list.add(toSpans(str))
    }
    return list
  }

  convertToDatabaseValue(entityProperty: List<SpanRepresentation>): string {
    return convert2Str(entityProperty)
  }
}

export class ListItemsConverter extends PropertyConverter<List<ListItem>,string> {
  convertToEntityProperty(databaseValue: string): List<ListItem> {
    let strList = split(databaseValue)
    let list = new List<ListItem>()
    for (let str of strList) {
      list.add(toListItem(str))
    }
    return list
  }

  convertToDatabaseValue(entityProperty: List<ListItem>): string {
    return convert2Str(entityProperty)
  }
}
